package com.everflourish.yeah100.act.menu;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.act.markingsystem.MarkingMenuActivity;
import com.everflourish.yeah100.adapter.DrawerLeftAdapter;
import com.everflourish.yeah100.entity.DrawerMenu;
import com.everflourish.yeah100.entity.DrawerMenuModel;
import com.everflourish.yeah100.http.HttpURL;
import com.everflourish.yeah100.http.ImageRequest;
import com.everflourish.yeah100.ui.CircleImageView;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.ImageSelectHolder;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.lapism.searchview.SearchView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.yalantis.ucrop.UCrop;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private DrawerLayout mDrawerLayout;
    private Toolbar mToolbar;
    private FloatingActionButton mFloatingActionButton;
    private FragmentExam mFragmentExam;   // 考试列表
    private FragmentQuestion mFragmentQuestion;  // 题库
    private FragmentSetting mFragmentSetting;  // 题库
    private Fragment isFragment;  // 记录当前的fragment
    private ListView mMenuList;
    private TextView mUserNameTv;
    private TextView mUserPhoneTv;
    private List<DrawerMenuModel> mDrwerList;
    private DrawerLeftAdapter leftAdapter;
    //    private String[] menu = {"考试列表", "题库", "蓝牙阅卷", "设置"};
    private String[] menu = {"考试列表", "题库", "设置"};
    //    private int[] drawableId = {R.mipmap.examiantion, R.mipmap.question_lib, R.mipmap.bluetooth_marking, R.mipmap.setting};
    private int[] drawableId = {R.mipmap.examiantion, R.mipmap.question_lib, R.mipmap.setting};
    private Menu mMenu;
    private SearchView mSearchView;
    private CircleImageView mUserHeaderIv;
    public ImageSelectHolder mImageHolder;
    private LoadDialog mLoadDialog;
    private Bitmap photoBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initData();
        initView();
        initFragment(savedInstanceState);
        setSearchView();
    }

    private void initData() {
        mDrwerList = new ArrayList<DrawerMenuModel>();
        for (int i = 0; i < 3; i++) {
            DrawerMenuModel menuModel = new DrawerMenuModel();
            menuModel.setDrawerMenu(new DrawerMenu(drawableId[i], menu[i]));
            menuModel.setIsChoose(false);
            mDrwerList.add(menuModel);
        }
    }

    private void setUserInfo() {
        if (TextUtils.isEmpty(Yeah100.loginInfo.userInfo.nickName)) {
            mUserNameTv.setText(Yeah100.loginInfo.userInfo.name);
        } else {
            mUserNameTv.setText(Yeah100.loginInfo.userInfo.nickName);
        }
        mUserPhoneTv.setText(Yeah100.loginInfo.userInfo.phoneNo);
        ImageRequest.getInstance(mQueue).get(mUserHeaderIv);
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.home_drawer_ly);
        mFloatingActionButton = (FloatingActionButton) findViewById(R.id.home_fab_button);
        mSearchView = (SearchView) findViewById(R.id.home_searchView);
        mMenuList = (ListView) findViewById(R.id.list_left_drawer);
        mUserHeaderIv = (CircleImageView) findViewById(R.id.image_head);
        mUserHeaderIv.setOnClickListener(this);
        leftAdapter = new DrawerLeftAdapter(mContext, mDrwerList);
        mMenuList.setAdapter(leftAdapter);
        mMenuList.setOnItemClickListener(this);
        mUserNameTv = (TextView) findViewById(R.id.home_user_name);
        mUserPhoneTv = (TextView) findViewById(R.id.home_phone);
        configView();
        if (Yeah100.loginInfo != null)
            setUserInfo();
    }

    private void configView() {
        mToolbar.setTitle("考试列表");
        setSupportActionBar(mToolbar);
        ActionBarDrawerToggle mActionBarDrawerToggle =
                new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mActionBarDrawerToggle.syncState();
        mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext,
                        MarkingMenuActivity.class);
                startActivityForResult(intent, 0x100);
            }
        });
    }

    private void setSearchView() {
        mSearchView.setVersion(SearchView.VERSION_MENU_ITEM);
        mSearchView.setVersionMargins(SearchView.VERSION_MARGINS_MENU_ITEM);
//        mSearchView.setVersionMargins(SearchView.THEME_LIGHT);
        mSearchView.setTextSize(16);
        mSearchView.setHint("搜索考试");
        mSearchView.setDivider(false);
        mSearchView.setVoice(false);
        mSearchView.setVoiceText("Set permission on Android 6+ !");
        mSearchView.setAnimationDuration(SearchView.ANIMATION_DURATION);
//        mSearchView.setShadowColor(ContextCompat.getColor(this, R.color.search_shadow_layout));
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                mSearchView.close(true);
                return searchData(query);
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    private boolean searchData(String query) {
        if (isFragment == mFragmentExam) {
            mFragmentExam.mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mFragmentExam.mSwipeRefreshLayout.setRefreshing(true);
                }
            });
            mFragmentExam.mExaminationName = query.toString().trim();
            mFragmentExam.searchExaminationInfo();
        } else if (isFragment == mFragmentQuestion) {
            mFragmentQuestion.mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mFragmentQuestion.mSwipeRefreshLayout.setRefreshing(true);
                }
            });
            mFragmentQuestion.tagName = query.toString().trim();
            mFragmentQuestion.getQuestionBankList();
        } else if (isFragment == mFragmentSetting) {

        }
        return true;
    }

    /**
     * fragment初始化
     *
     * @param savedInstanceState
     */
    public void initFragment(Bundle savedInstanceState) {
        //判断activity是否重建，如果不是，则不需要重新建立fragment.
        if (savedInstanceState == null) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            if (mFragmentExam == null) {
                mFragmentExam = new FragmentExam();
            }
            isFragment = mFragmentExam;
            ft.replace(R.id.content_frame, mFragmentExam).commit();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        for (DrawerMenuModel model : mDrwerList) {
            model.setIsChoose(false);
        }
        mDrwerList.get(position).setIsChoose(true);
        leftAdapter.notifyDataSetChanged();
        selectMenuItem(position);
    }

    /**
     * 选择菜单item
     *
     * @param position
     */
    private void selectMenuItem(int position) {
        switch (position) {
            case 0:
                showEditMenu();
                if (mFragmentExam == null) {
                    mFragmentExam = new FragmentExam();
                }
                mToolbar.setTitle("考试列表");
                mSearchView.setHint("搜索考试");
                mFloatingActionButton.setVisibility(View.VISIBLE);
                switchContent(isFragment, mFragmentExam);
                break;
            case 1:
                showEditMenu();
                if (mFragmentQuestion == null) {
                    mFragmentQuestion = new FragmentQuestion();
                }
                mToolbar.setTitle("题库");
                mSearchView.setHint("搜索题库");
                mFloatingActionButton.setVisibility(View.GONE);
                switchContent(isFragment, mFragmentQuestion);
                break;
//            case 2:
//                MyToast.showLong(mContext, "该入口未开放，请从进入考试进行阅卷");
//                return;
            case 2:
                hiddenEditMenu();
                if (mFragmentSetting == null) {
                    mFragmentSetting = new FragmentSetting();
                }
                mToolbar.setTitle("设置");
                mFloatingActionButton.setVisibility(View.GONE);
                switchContent(isFragment, mFragmentSetting);
                break;
            default:
                break;
        }
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }

    /**
     * 当fragment进行切换时，采用隐藏与显示的方法加载fragment以防止数据的重复加载
     *
     * @param from
     * @param to
     */
    public void switchContent(Fragment from, Fragment to) {
        if (isFragment != to) {
            isFragment = to;
            FragmentManager fm = getSupportFragmentManager();
            //添加渐隐渐现的动画
            FragmentTransaction ft = fm.beginTransaction();
            if (!to.isAdded()) {    // 先判断是否被add过
                ft.hide(from).add(R.id.content_frame, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                ft.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x100) {
                if (data.getBooleanExtra(IntentUtil.IS_UPDATE, false)) {
                    mFragmentExam.mSwipeRefreshLayout.setRefreshing(true);
                    mFragmentExam.mRefreshListener.onRefresh();
                }
            } else if (requestCode == 0x180) {
                if (data.getBooleanExtra(IntentUtil.QUESTION_IS_UPDATE, false)) {
                    mFragmentQuestion.mSwipeRefreshLayout.setRefreshing(true);
                    mFragmentQuestion.mRefreshListener.onRefresh();
                }
            } else if (requestCode == ImageSelectHolder.REQUEST_SELECT_PICTURE
                    || requestCode == ImageSelectHolder.CAMERA_WITH_DATA) {
                Uri selectedUri = null;
                if (data == null) {
                    selectedUri = Uri.fromFile(mImageHolder.mTempFile);
//                    MyToast.showLong(mContext, selectedUri + "");
                    mImageHolder.startCropActivity(selectedUri);
                } else {
                    selectedUri = data.getData();
                    if (selectedUri != null) {
                        mImageHolder.startCropActivity(data.getData());
                    } else {
                        selectedUri = Uri.fromFile(mImageHolder.mTempFile);
//                        MyToast.showLong(mContext, selectedUri + "");
                        mImageHolder.startCropActivity(selectedUri);
                    }
                }
            } else if (requestCode == UCrop.REQUEST_CROP) {
                try {
                    handleCropResult(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenu = menu;
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_indistinct_search:
                mSearchView.open(true, item);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 隐藏toolbar图标
     */
    private void hiddenEditMenu() {
        if (null != mMenu) {
            for (int i = 0; i < mMenu.size(); i++) {
                mMenu.getItem(i).setVisible(false);
                mMenu.getItem(i).setEnabled(false);
            }
        }
    }

    /**
     * 显示toolbar图标
     */
    private void showEditMenu() {
        if (null != mMenu) {
            for (int i = 0; i < mMenu.size(); i++) {
                mMenu.getItem(i).setVisible(true);
                mMenu.getItem(i).setEnabled(true);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_head:
                mImageHolder = new ImageSelectHolder(HomeActivity.this);
                mImageHolder.open(v, ImageSelectHolder.IMAGE_HEADER);
                break;
        }
    }

    public void handleCropResult(@NonNull Intent result) throws Exception {
        final Uri mCropUri = UCrop.getOutput(result);
        try {
            if (mCropUri != null) {
                photoBitmap = BitmapFactory.decodeStream(this
                        .getContentResolver().openInputStream(mCropUri));
                uploadImage(photoBitmap, mUserHeaderIv);
            } else {
                Toast.makeText(this, "裁剪图片失败！", Toast.LENGTH_LONG)
                        .show();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ImageSelectHolder.isDisable) {
                if (ImageSelectHolder.mTempFile != null && ImageSelectHolder.mTempFile.exists()) {
                    mImageHolder.mTempFile.delete();
                }
                if (mCropUri != null) {
                    File cropFile = new File(mCropUri.getPath());
                    if (cropFile != null && cropFile.exists()) {
                        cropFile.delete();
                    }
                }
            }
        }
    }

    /**
     * 上传头像
     *
     * @param bitmap
     * @throws Exception
     */
    public void uploadImage(Bitmap bitmap, final ImageView userImageIv)
            throws Exception {
        String name = Yeah100.loginInfo.userInfo.name;
        String encoderName = CommonUtil.string2MD5(name);
        final File file = new File(Environment.getExternalStorageDirectory()
                + "/" + encoderName + "_" + System.currentTimeMillis() + ".jpg");
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        RequestParams params = new RequestParams();
        params.addHeader("tokenId", Yeah100.loginInfo.tokenId);
        HttpUtils httpUtils = new HttpUtils();
        String http = new HttpURL().URL_IMAGE_UPDATE;
        params.addBodyParameter("outputStream", file);

        httpUtils.send(HttpMethod.POST, http, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                        LogUtil.d(total + ":" + current + ":" + isUploading);
                    }

                    @Override
                    public void onStart() {
                        mLoadDialog = LoadDialog.show(mContext, null, "正在上传...", false);
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        if (arg0 != null && arg0.getMessage() != null) {
                            if (arg0.getMessage().contains(
                                    "HttpHostConnectException")) {
                                MyToast.showShort(mContext, "网络断开!");
                            }
                        } else {
                            MyToast.showLong(mContext, "上传头像失败");
                        }
                        LoadDialog.dismiss(mLoadDialog);
                        if (file.exists()) {
                            file.delete();
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> response) {
                        String result = response.result;
                        String resultCode = null;
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            resultCode = jsonObject
                                    .getString(Constant.RESULT_CODE);
                            if (resultCode
                                    .equals(ResultCode.result_ok.resultCode)) {
                                // 上传图片成功，更新用户信息
                                String imageId = jsonObject
                                        .getString("filePath");
                                if (StringUtil.stringIsNull(imageId)) {
                                    MyToast.showShort(mContext, "上传图片失败");
                                    return;
                                }
                                Yeah100.loginInfo.userInfo.photoId = imageId;
                                // 上传头像成功
                                Yeah100.isUpdateImageId = true;
                                Yeah100.userImageUrl = new HttpURL().URL_IMAGE_GET
                                        + Yeah100.loginInfo.userInfo.photoId
                                        .replace(".jpg", "");
                                MyToast.showShort(mContext, "上传头像成功");
                                ImageRequest.getInstance(mQueue).get(
                                        userImageIv);
                            } else if (resultCode
                                    .equals(ResultCode.result_000001E.resultCode)) {
                                MyToast.showShort(mContext, R.string.user_info_03051_000001E);
                            } else if (resultCode
                                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                                MyToast.showShort(mContext, R.string.user_info_030599_999999E);
                            } else {
                                MyToast.showShort(mContext, "上传头像失败");
                            }
                        } catch (JSONException e) {
                            LogUtil.e("JSON异常", e);
                            MyToast.showShort(mContext, "上传图片失败");
                        } finally {
                            // 上传成功后，设置用户信息
                            if (file.exists()) {
                                file.delete();
                            }
                            LoadDialog.dismiss(mLoadDialog);
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (photoBitmap != null && !photoBitmap.isRecycled()) {
            // 回收并且置为null
            photoBitmap.recycle();
            photoBitmap = null;
        }
    }
}